package com.dd.machine.main.desktop;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.baidu.tts.client.SpeechSynthesizer;
import com.cn.dd.machine.R;
import com.dd.machine.base.activity.BaseActivity;
import com.dd.machine.base.app.MyApplication;
import com.dd.machine.base.net.URLManager;
import com.dd.machine.base.utils.DeviceInfo;
import com.dd.machine.base.utils.ImageLoaderUtils;
import com.dd.machine.main.HardwareUtils.CardRead;
import com.dd.machine.main.HardwareUtils.LockUtils;
import com.dd.machine.main.Interface.HardwareInterface;
import com.dd.machine.main.commons.PollingUtils;
import com.dd.machine.base.view.MyNewViewPager;
import com.dd.machine.greendao.gen.AppAdverDao;
import com.dd.machine.greendao.gen.AppGoodsKindDao;
import com.dd.machine.greendao.gen.EqueipmentDao;
import com.dd.machine.greendao.gen.OrderFormDao;
import com.dd.machine.main.commons.SPUtils;
import com.dd.machine.main.commons.VoiceUtils;
import com.dd.machine.main.service.DelteDataService;
import com.dd.machine.main.service.PollingService;
import com.dd.machine.main.user.GoodsKindActivity;
import com.dd.machine.main.user.LoginActivity;
import com.dd.machine.main.user.adapter.ImagePaperAdapter;
import com.dd.machine.main.user.adapter.PictureAdapter;
import com.dd.machine.main.user.model.AppAdver;
import com.dd.machine.main.user.model.AppGoodsKind;
import com.dd.machine.main.user.model.Equeipment;
import com.dd.machine.main.user.model.OrderForm;
import com.ensentec.Lib.EnsenLib;
import com.iflytek.cloud.thirdparty.V;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.greendao.query.Query;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;

import static com.dd.machine.base.net.NetUtils.isNetworkAvailable;
import static com.dd.machine.base.net.URLManager.APPCONFIG;
import static com.dd.machine.base.net.URLManager.CARDLOGIN;
import static com.dd.machine.base.net.URLManager.GETMESSAGEEQUIPMENT;
import static com.dd.machine.base.utils.ToastUtil.showShortToast;
import static com.dd.machine.main.commons.PostServer.pushId;

/**
 * Created by Administrator on 2017/6/30.
 */

public class DeskTopActivity extends BaseActivity{

    @Bind(R.id.activity_top)
    RelativeLayout activity_top;
    @Bind(R.id.card_btn)
    Button cardBtn;
    @Bind(R.id.wx_btn)
    Button wxBtn;
    static ImageView no_banner;


    PopupWindow popupWindow;
    private RelativeLayout popup_close_rel;
    private ImageView qr_code_iv;
    private TextView login_tv;
    private EditText ic_num_et;
    private LinearLayout ic_Lin;
    private static Context context;

    //轮播图
    private static List<AppAdver> adverList;

    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;



    boolean ret = true;

    private static final int UPDATADATA = 0;
    private static final int BDPRINT = 1;
    private static final int BANNER=2;
    private static final int ISINTENT = 3;
    private static final int BANNER_START = 4;

    private SpeechSynthesizer mSpeechSynthesizer;

    static boolean isIntent = true;


    //轮播广告
    private LayoutInflater inflater;

    private ViewPager mviewPager;
    private RelativeLayout slideView;
    /**用于小圆点图片*/
    private List<ImageView> dotViewList;
    /**用于存放轮播效果图片*/
    private List<ImageView> list;

    LinearLayout dotLayout;

    private int currentItem  = 0;//当前页面

    boolean isAutoPlay = true;//是否自动轮播

    private ScheduledExecutorService scheduledExecutorService;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_desktop);
        context = DeskTopActivity.this;
        ButterKnife.bind(this);
        VoiceUtils voiceUtils = MyApplication.getInstances().getVoiceUtils();
        mSpeechSynthesizer = voiceUtils.getSyntheszer();
        getAppConfig();
        initViews();
//        initPolling();//使用闹钟，开启轮询   在application中开启
//        initDeletePolling();在application中开启
        //判断是不是第一次打开应用，是的话，获取设备信息并保存
        if (SPUtils.firstOpen(this)){
            Log.e("==获取message","获取设备信息");
            getEquementMessage();
        }

        initPopupWindow();
        initBroadCastRecever();



        //监听获取卡号 并验证
        EnsenLib.getInstance().setCardReadSuccessListener(new EnsenLib.OnCardReadSuccess() {
            @Override
            public void onCardReadSuccess(final String cardNo) {
                Verification(cardNo);
            }
        });

    }



    //初始化控件，上传pushId
    private void initViews(){
        String deviceToken = DeviceInfo.getDEVICE_ID(this);
        String pushId = JPushInterface.getRegistrationID(getApplicationContext());
        int currentapiVersion=android.os.Build.VERSION.SDK_INT;
        pushId(deviceToken,pushId,"androidAPI"+currentapiVersion);//发送pushid
        no_banner = (ImageView) findViewById(R.id.no_banner);

        inflater = LayoutInflater.from(DeskTopActivity.this);

        mviewPager = (ViewPager) findViewById(R.id.myVp);
        dotLayout = (LinearLayout)findViewById(R.id.dotLayout);
        slideView = (RelativeLayout) findViewById(R.id.slideView);
        dotLayout.removeAllViews();

        if(isAutoPlay){
            startPlay();
        }


    }

    private void startPlay(){
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 5, TimeUnit.SECONDS);
        //根据他的参数说明，第一个参数是执行的任务，第二个参数是第一次执行的间隔，第三个参数是执行任务的周期；
    }

    private class SlideShowTask implements Runnable{

        @Override
        public void run() {
            // TODO Auto-generated method stub
            synchronized (mviewPager) {
                currentItem = (currentItem+1)%list.size();
                handler.sendEmptyMessage(BANNER_START);
            }
        }
    }

    //根据设备号，获取设备信息
    private void getEquementMessage() {
        OkHttpUtils.get()
                .url(GETMESSAGEEQUIPMENT+"JINANDINGGAO")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
//                        Log.e("==获取onError",e.getMessage());
                        getEquementMessage();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        SPUtils.setFristOpen(DeskTopActivity.this,false);
                        Log.e("==获取onResponse",response);
                        json(response);
                    }
                });
    }

    private void json(String response) {
        try {
            Equeipment equeipment = new Equeipment();
            JSONObject object = new JSONObject(response);
            equeipment.setEId(object.getInt("id"));
            equeipment.setName(object.optString("name"));
            equeipment.setType(object.optString("type"));
            equeipment.setAddress(object.optString("address"));
            equeipment.setEquipmentNo(object.optString("equipmentNo"));
            equeipment.setMakerPhone(object.optString("makerPhone"));
            equeipment.setOnlineStatus(object.optInt("onlineStatus"));
            equeipment.setEquipmentStatus(object.optInt("equipmentStatus"));
            equeipment.setLat(object.optDouble("lat"));
            equeipment.setLng(object.optDouble("lng"));

            //保存设备信息，不出意外就是长期保存
            cacheEqMessage(equeipment);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //接收更新数据的广播，更新UI，关闭服务，并注销广播
    private void initBroadCastRecever() {
        broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("PollingService");
        intentFilter.addAction("DeleteService");
        intentFilter.addAction("network");
        intentFilter.addAction("receiver");
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("PollingService".equals(intent.getAction())) {
                    Message msg = Message.obtain();
                    msg.what = BANNER;
                    handler.sendMessage(msg);
                    Intent stop = new Intent();
                    stop.setAction("com.dd.machine.main.service.PollingService");
                    stopService(stop);
                } else if ("DeleteService".equals(intent.getAction())) {
                    Intent stop = new Intent();
                    stop.setAction("com.dd.machine.main.service.DelteDataService");
                    stopService(stop);
                } else if ("network".equals(intent.getAction())) {
                    Bundle bundle = intent.getExtras();
                    isIntent =  bundle.getBoolean("isNetworkAvailable");
                    Log.e("===测试网络", isIntent +"");
                    Message msg = Message.obtain();
                    msg.what = ISINTENT;
                    handler.sendMessage(msg);
                } else if ("receiver".equals(intent.getAction())) {
                    if (popupWindow.isShowing()) {
                        popupWindow.dismiss();
                    }
                    finish();

                }

            }
        };
        broadcastManager.registerReceiver(broadcastReceiver,intentFilter);
    }
    private void initPopupWindow() {
        View view = LayoutInflater.from(this).inflate(R.layout.popup_wx_login,null);
        popup_close_rel = (RelativeLayout) view.findViewById(R.id.popup_close_rel);
        qr_code_iv = (ImageView) view.findViewById(R.id.qr_code_iv);
        login_tv = (TextView) view.findViewById(R.id.login_tv);
//        ic_num_et = (EditText) view.findViewById(R.id.ic_num_et);
        ic_Lin = (LinearLayout)view.findViewById(R.id.ic_Lin);
        popupWindow = new PopupWindow(view, RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT, false);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        ColorDrawable dw = new ColorDrawable(0x00000000);
        popupWindow.setBackgroundDrawable(dw);
        popup_close_rel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
                ret = false;
                SPUtils.setReceiver(DeskTopActivity.this,false);
            }
        });
    }

    private void getAppConfig() {
        Log.e("===activity","===resuest");
        OkHttpUtils.post()
                .url(APPCONFIG)
                .addParams("platform","android")
                .addParams("equipmentNo","JINANDINGGAO")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
//                        showShortToast(context,e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("===response",response);
                        json2List(response);
                    }
                });
        Message msg = Message.obtain();
        msg.what = BANNER;
        handler.sendMessage(msg);
    }

    private void json2List(String response) {
        try {
            JSONObject object = new JSONObject(response);
            JSONArray jsonArray = object.optJSONArray("app_fix_price");
            JSONArray array = object.optJSONArray("app_adver");
            String qrCode  = object.optString("app_wechat_bar_code");
            Log.e("===qrcode",qrCode);
            SPUtils.setQRCode(this,qrCode);
            AppGoodsKind kind;
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.optJSONObject(i);
                kind = new AppGoodsKind();
                kind.setGoodsId(jsonObject.optInt("id"));
                kind.setAreaId(jsonObject.optInt("areaId"));
                kind.setImg(jsonObject.optString("img"));
                kind.setTypeName(jsonObject.optString("typeName"));
                if ((jsonObject.opt("parentId")+"").equals("null")) {
                    kind.setParentId("no");
                }else {
                    kind.setParentId(jsonObject.opt("parentId")+"");
                }
                kind.setCreateTime(jsonObject.optLong("createTime"));
                kind.setUnitPrice(jsonObject.optDouble("unitPrice"));
                kind.setUpdateTime(jsonObject.optLong("updateTime"));
                kind.setDisable(jsonObject.optInt("disable"));
                kind.setSequence(jsonObject.optInt("sequence"));
                kind.setUpdateBy(jsonObject.optInt("updateBy"));
                cacheAppInfo(kind);

            }
            for (int i = 0; i < array.length(); i++) {
                JSONObject object1 = array.getJSONObject(i);
                AppAdver appAdver = new AppAdver();
                appAdver.setAdvId(i+1);
                appAdver.setImgUrl(object1.optString("imgUrl"));
                appAdver.setGotoUrl(object1.optString("gotoUrl"));
                appAdver.setSequence(object1.optInt("sequence"));
                cacheAdvInfo(appAdver);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case BANNER_START:
                    mviewPager.setCurrentItem(currentItem);
                    break;
                case BANNER://轮播图
                    AppAdverDao dao = MyApplication.getInstances().getDaoSession().getAppAdverDao();
                    adverList = new ArrayList<>();
                    adverList = dao.loadAll();
                    Log.e("--->广告数量",adverList.size()+"");
                    dotViewList = new ArrayList<>();
                    list = new ArrayList<>();
                    if (adverList.size()>0) {
                        for (int i = 0; i < adverList.size(); i++) {
                            ImageView img = (ImageView) inflater.inflate(R.layout.scroll_vew_item, null);
                            ImageLoaderUtils.display(adverList.get(i).getImgUrl(),img);
                            list.add(img);
                        }
                        if (list.size()>0) {
                            for (int i = 0; i < list.size(); i++) {
                                ImageView dotView = new ImageView(DeskTopActivity.this);
                                LinearLayout.LayoutParams params =
                                        new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

                                params.leftMargin = 15;//设置小圆点的外边距
                                params.rightMargin = 15;

//                                params.height = 40;//设置小圆点的大小
//                                params.width = 40;

                                if(i == 0){
                                    dotView.setBackgroundResource(R.drawable.round_selseted);
                                }else{

                                    dotView.setBackgroundResource(R.drawable.round_noselested);
                                }
                                dotLayout.addView(dotView, params);

                                dotViewList.add(dotView);
                                //上面是动态添加小圆点
                            }
                        }

                        ImagePaperAdapter adapter = new ImagePaperAdapter((ArrayList)list);

                        mviewPager.setAdapter(adapter);
                        mviewPager.setCurrentItem(0);
                        mviewPager.setOnPageChangeListener(new MyPageChangeListener());
                    }else {
                        slideView.setVisibility(View.GONE);
                        no_banner.setVisibility(View.VISIBLE);
                    }
                    break;
                case UPDATADATA://更新数据
                    break;
                case BDPRINT://百度语音
//                    String message = (String) msg.obj;
//                    if (message != null) {
//                        Log.e("==百度语音消息", message);
////                        Toast.makeText(DeskTopActivity.this, message, Toast.LENGTH_SHORT).show();
//                    }
                    break;
                case ISINTENT:
                    if (!isIntent) {//网络不可用

                    }else {

                    }
                    break;

            }
        }
    };

    private class MyPageChangeListener implements ViewPager.OnPageChangeListener {

        boolean isAutoPlay = false;
        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub
            switch (arg0) {
                case 1:// 手势滑动，空闲中
                    isAutoPlay = false;
                    System.out.println(" 手势滑动，空闲中");
                    break;
                case 2:// 界面切换中
                    isAutoPlay = true;
                    System.out.println(" 界面切换中");
                    break;
                case 0:// 滑动结束，即切换完毕或者加载完毕
                    // 当前为最后一张，此时从右向左滑，则切换到第一张
                    if (mviewPager.getCurrentItem() == mviewPager.getAdapter().getCount() - 1 && !isAutoPlay) {
                        mviewPager.setCurrentItem(0);
                        System.out.println(" 滑动到最后一张");
                    }
                    // 当前为第一张，此时从左向右滑，则切换到最后一张
                    else if (mviewPager.getCurrentItem() == 0 && !isAutoPlay) {
                        mviewPager.setCurrentItem(mviewPager.getAdapter().getCount() - 1);
                        System.out.println(" 滑动到第一张");
                    }
                    break;
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onPageSelected(int pos) {
            // TODO Auto-generated method stub
            //这里面动态改变小圆点的被背景，来实现效果
            currentItem = pos;
            for(int i=0;i < dotViewList.size();i++){
                if(i == pos){
                    ((View)dotViewList.get(pos)).setBackgroundResource(R.drawable.round_selseted);
                }else {
                    ((View)dotViewList.get(i)).setBackgroundResource(R.drawable.round_noselested);
                }
            }
        }

    }

    @OnClick({R.id.card_btn, R.id.wx_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.card_btn://刷卡登录
                login_tv.setVisibility(View.GONE);
                ic_Lin.setVisibility(View.VISIBLE);
                qr_code_iv.setImageResource(R.drawable.shuakalogin);
                backgroundAlpha(0.4f);
                popupWindow.showAtLocation(activity_top, Gravity.CENTER,0,0);
                break;
            case R.id.wx_btn://微信登录
                ImageLoaderUtils.display(SPUtils.getQRCode(this),qr_code_iv);
                //设置为可接收来自极光推送的消息
                SPUtils.setReceiver(DeskTopActivity.this,true);
                backgroundAlpha(0.4f);
                login_tv.setVisibility(View.VISIBLE);
                ic_Lin.setVisibility(View.GONE);
                popupWindow.showAtLocation(activity_top, Gravity.CENTER,0,0);
                ret = true;
                startRequest();
                break;
        }
    }

    int count = 0;
    private void startRequest(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count<12){
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (ret){
                        count = count+1;
                        requset();
                    }
                }
            }
        }).start();
    }

    private void requset(){
        OkHttpUtils.get()
                .url(URLManager.GETBYEQUIPMENT+"JINANDINGGAO")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("==requset onError",e.toString());
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("==requset onResponse",response);
                        Log.e("==requset LENTH",response.equals("{}")+"");
                        if (!response.equals("{}")) {
                            ret = false;
                            SPUtils.setReceiver(DeskTopActivity.this,false);
                        }
                    }
                });
    }

    //验证ic卡号是否绑定手机号
    private void Verification(final String cardCode) {
        Log.e("==卡号",cardCode);
        OkHttpUtils.get()
                .url(CARDLOGIN + cardCode)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("==cardlogin-onError", e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("==cardlogin-onResponse", response);
                        try {
                            JSONObject object = new JSONObject(response);
                            String uesrid = object.optString("userId");
                            if ("0".equals(uesrid)) {//没有绑定手机号，进入手机号绑定页面，进行绑定认证
                                Intent intent = new Intent(context, LoginActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putString("number", cardCode);
                                intent.putExtras(bundle);
                                startActivity(intent);
                                finish();

                            }else {//已经绑定手机号，直接登录成功，进入分类页面
                                JSONObject jsonObject = object.optJSONObject("userCard");
                                String userId = jsonObject.optString("userId");
                                Intent intent = new Intent(context, GoodsKindActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putString("userId",userId);
                                intent.putExtras(bundle);
                                startActivity(intent);
                                finish();

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }


    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }


    public void cacheAppInfo(AppGoodsKind kind){
        AppGoodsKind old = getInfoFromCache(kind.getGoodsId()+"");
        if (old!=null) {
            kind.setId(old.getId());
        }
        AppGoodsKindDao appDao = MyApplication.getInstances().getDaoSession().getAppGoodsKindDao();
        appDao.save(kind);

    }

    public void cacheAdvInfo(AppAdver appAdver){
        AppAdver old = getAdvInfoFromCache(appAdver.getAdvId()+"");
        if (old!=null) {
            appAdver.setId(old.getId());
        }
        AppAdverDao dao = MyApplication.getInstances().getDaoSession().getAppAdverDao();
        dao.save(appAdver);
    }

    public AppAdver getAdvInfoFromCache(String id){
        AppAdverDao userDao = MyApplication.getInstances().getDaoSession().getAppAdverDao();
        Query<AppAdver> query = userDao.queryBuilder().where(AppAdverDao.Properties.AdvId.eq(id))
                .orderDesc(AppAdverDao.Properties.AdvId).build();
        return query.unique();

    }
    public AppGoodsKind getInfoFromCache(String memberId) {
        AppGoodsKindDao userDao = MyApplication.getInstances().getDaoSession().getAppGoodsKindDao();
        Query<AppGoodsKind> query = userDao.queryBuilder().where(AppGoodsKindDao.Properties.GoodsId.eq(memberId))
                .orderDesc(AppGoodsKindDao.Properties.GoodsId).build();
        return query.unique();
    }

    public void cacheEqMessage(Equeipment equeipment){
        Equeipment old = getInfoFromEqCache(equeipment.getEId()+"");
        if (old!=null) {
            equeipment.setId(old.getId());
        }
        EqueipmentDao dao = MyApplication.getInstances().getDaoSession().getEqueipmentDao();
        dao.save(equeipment);
    }
    public Equeipment getInfoFromEqCache(String eqid){
        EqueipmentDao dao = MyApplication.getInstances().getDaoSession().getEqueipmentDao();
        Query<Equeipment> query = dao.queryBuilder().where(EqueipmentDao.Properties.EId.eq(eqid))
                .orderDesc(EqueipmentDao.Properties.EId).build();
        return query.unique();
    }



    @Override
    protected void onPause() {
        super.onPause();
        ret = false;
        SPUtils.setReceiver(this,false);
        if (popupWindow.isShowing()){
            popupWindow.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ret = false;
        SPUtils.setReceiver(this,false);
        if (popupWindow.isShowing()){
            popupWindow.dismiss();
        }
    }
}
